<script>
/**
 * 选项
 * @typedef { Object } MyOptions
 * @type { Object }
 * @property { String | Number } options.value
 * @property { String | Number } options.title
 */
export default {
    name: 'TXSelect',
    emits: ['select'],
    props: {
      title: {
        type: String,
        default: '默认'
      },
      /**
       * @type {Array.<MyOptions>}
       */
      options: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        visible: false,
        value: ''
      }
    },
    methods: {
      handleVisible(e) {
        if (e.target.className === 'tx-select-title') {
          this.visible = true
          const toggleVisible = (ev) => {
            if (e.target !== ev.target) {
              this.visible = false
              document.removeEventListener('click', toggleVisible)
            }
          }
          // 菜单显示时添加全局点击事件使得点击任意地方都可隐藏菜单
          if (this.visible) {
            document.addEventListener('click', toggleVisible)
          }
        } else if (e.target.className === 'tx-select-option') {
          e.stopPropagation()
        }
      },
      handleSelect (selectRow) {
        this.$emit('select', Object.assign({}, selectRow))
      }
    }
  }
</script>

<template>
  <div class="tx-select" :class="{ 'is-active': visible }" @click="handleVisible">
    <span class="tx-select-title">{{ title }}</span>
    <ul class="tx-select-container" v-show="visible" >
      <li v-for="option in options" class="tx-select-option" :class="{ 'is-active': value === option.value }" @click="handleSelect(option)">{{ option.title }}</li>
    </ul>
  </div>
</template>


<style scoped lang="less">
  @import '../../css/index';
</style>